<template>
  <div class="app-container">
    <el-form
      ref="form"
      v-loading="loading"
      :model="form"
      :rules="rules"
      label-width="160px"
      label-position="right"
      size="small"
    >
      <el-row :gutter="15">
        <template>
          <el-col :span="24">
            <MmvTitle title="订单信息"></MmvTitle>
          </el-col>
          <el-col :span="12">
            <el-form-item label="取还车地址" prop="storeId">
              <el-input
                v-model="form.storeName"
                style="width: 100%; margin-right: 15px"
                placeholder="请选择门店"
                @click.native="showmendian = true"
                readonly
              >
                <el-button
                  icon="el-icon-search"
                  slot="append"
                  @click="showmendian = true"
                ></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="租赁时间" prop="startTime">
<!--              :picker-options="{ disabledDate }"-->
              <el-date-picker
                style="width: 100%; margin-right: 15px"
                v-model="form.startTime"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="租赁时间"
                type="datetime"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="租期（月）" prop="tenancyTerm">
              <el-input-number
                v-model="form.tenancyTerm"
                :min="1"
                :max="36"
                label="租期（月）"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </template>
        <template v-if="showcheliangform">
          <el-col :span="24">
            <MmvTitle title="费用信息"></MmvTitle>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车型方案" prop="longPlanId">
              <el-input
                :value="chexing.modelInfo"
                placeholder="请选择车型"
                style="width: 100%; margin-right: 15px"
                @click.native="clickshowchexing"
                readonly
              >
                <el-button
                  icon="el-icon-search"
                  slot="append"
                  @click="clickshowchexing"
                ></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车辆押金（元）" prop="longPlanId">
              <el-input
                v-model="formData.deposit"
                placeholder="请选择车型"
                style="width: 100%; margin-right: 15px"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="月租金（元）" prop="longPlanId">
              <el-input
                v-model="chexing.monthlyRent"
                placeholder="请选择车型"
                style="width: 100%; margin-right: 15px"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="租赁费用（元）" prop="longPlanId">
              <el-input
                v-model="formData.amount"
                placeholder="请选择车型"
                style="width: 100%; margin-right: 15px"
              ></el-input>
            </el-form-item>
          </el-col>
        </template>
        <template v-if="showkehuform">
          <el-col :span="24">
            <MmvTitle title="客户信息"></MmvTitle>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选择客户" prop="memberNo">
              <el-input
                :value="kehu.memberName"
                style="width: 100%; margin-right: 15px"
                placeholder="请选择客户"
                @click.native="showkehu = true"
                readonly
              >
                <el-button
                  icon="el-icon-search"
                  slot="append"
                  @click="showkehu = true"
                ></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户类型" prop="memberType">
              <el-input
                :value="kehu.memberType | memberType"
                style="width: 100%; margin-right: 15px"
                placeholder="请选择客户"
                readonly
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户来源" prop="memberSource">
              <el-input
                :value="kehu.memberSource | memberSource"
                style="width: 100%; margin-right: 15px"
                placeholder="请选择客户"
                readonly
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contactPhone">
              <el-input
                :value="kehu.contactPhone"
                style="width: 100%; margin-right: 15px"
                placeholder="请选择客户"
                readonly
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="联系地址" prop="contactAddress">
              <el-input
                :value="kehu.contactAddress"
                style="width: 100%; margin-right: 15px"
                placeholder="请选择客户"
                readonly
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证件号码" prop="cardId">
              <el-input
                :value="kehu.cardId"
                style="width: 100%; margin-right: 15px"
                placeholder="请选择客户"
                readonly
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="失效日期" prop="cardValidity">
              <el-input
                :value="kehu.cardValidity"
                style="width: 100%; margin-right: 15px"
                placeholder="请选择客户"
                readonly
              >
              </el-input>
            </el-form-item>
          </el-col>
        </template>
        <template v-if="showqitaform">
          <el-col :span="24">
            <MmvTitle title="其他信息"></MmvTitle>
          </el-col>
          <el-col :span="24">
            <el-form-item label="押金支付类型" prop="depositPayType">
              <el-radio-group v-model.number="form.depositPayType">
                <!-- <template v-for="item in dict.type.sys_pay_type">
                                    <el-radio :label="item.value" :key="item.value">{{item.label}}</el-radio>
                                </template> -->
<!--                <el-radio :label="1">线上</el-radio>-->
                <el-radio :label="2">线下</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="paymentSupport.length">
            <el-form-item label="支付方式" prop="methodPayment">
              <el-radio-group v-model.number="form.methodPayment">
                <template v-for="(item, index) in dict.type.payment_support">
                  <el-radio
                    :label="Number(item.value)"
                    :key="index"
                    v-if="paymentSupport.includes(Number(item.value))"
                    >{{ item.label }}</el-radio
                  >
                </template>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </template>
      </el-row>
      <!-- <pre>{{chexing}}</pre> -->
      <!-- <pre>{{formData}}</pre> -->
    </el-form>
    <!-- 选择门店 -->
    <MmvMendian :show="showmendian" @success="submitmendian"></MmvMendian>
    <!-- 选择车型 -->
    <el-dialog
      title="选择车型"
      width="1000px"
      destroy-on-close
      append-to-body
      :visible.sync="showchexing"
    >
      <MmvChexing
        ref="MmvChexing"
        @checked="submitchenxing"
        :storeId="form.storeId"
        v-if="showchexing"
      ></MmvChexing>
    </el-dialog>
    <!-- 选择客户 -->
    <el-dialog
      title="选择客户"
      width="1000px"
      destroy-on-close
      append-to-body
      :visible.sync="showkehu"
    >
      <MmvMember
        ref="MmvMember"
        v-if="showkehu"
        @success="submitkehu"
      ></MmvMember>
    </el-dialog>
  </div>
</template>

<script>
import * as utils from '@/utils'
import * as api from '@/api/longOrder/index'
import MmvTitle from '@/components/MmvUI/MmvTitle.vue'
import MmvMendian from '@/views/components/selectStore.vue'
import MmvChexing from './components/chexing.vue'
import MmvMember from '@/views/components/selectMember.vue'

export default {
  components: {
    MmvTitle,
    MmvMendian,
    MmvChexing,
    MmvMember,
  },
  dicts: [
    'sys_order_source',
    'sys_pay_type',
    'order_payWay',
    'payment_support',
  ],
  filters: {
    memberType(val) {
      return (
        {
          1: '企业',
          2: '个人',
        }[Number(val)] || ''
      )
    },
    memberSource(val) {
      return (
        {
          1: '搜索',
          2: '分享',
          3: '扫码',
          4: '手动录入',
        }[Number(val)] || ''
      )
    },
  },
  props: ['id'],
  data() {
    return {
      loading: false,
      showmendian: false,
      showchexing: false,
      showkehu: false,
      paymentSupport: [],
      chexing: {},
      kehu: {},
      // 表单字段预览。调用接口并非传入此对象，仅作为预览。
      form: {
        longPlanId: '', // "PL1648623360350678022",//方案id
        storeId: '', // "09df69b860c241ec8ef1cbbd43621fff", // 取还车门店id
        storeName: '', // "09df69b860c241ec8ef1cbbd43621fff", //取还车门店
        startTime: '', // "2021-03-30 00:00:00", //开始时间
        endTime: '', // "2022-03-30 00:00:00", //结束时间
        tenancyTerm: '', // "12", // |租期
        amount: '', // "15000", // 支付总金额
        deposit: '', // "1000", // 车辆押金
        rent: '', // "14000", // 租金
        depositPayType: 2, // "2", //押金支付类型（1.线上 2.线下 ）
        methodPayment: 1, // "1", // |支付方式  1.月付 2.一次性
        memberNo: '', // "M16485202951627832"
      },
      rules: {
        storeId: [{ required: true, message: '门店必选！' }],
        longPlanId: [{ required: true, message: '车辆必选！' }],
        memberNo: [{ required: true, message: '客户必选！' }],
        startTime: [{ required: true, message: '租赁时间必填！' }],
        tenancyTerm: [
          { required: true, message: '租期必填！' },
          {
            validator: (rule, value, callback) => {
              if (!Number(value) || Number(value) < 0) {
                callback(new Error('租期只能为正整数！'))
              } else {
                callback()
              }
            },
          },
        ],
        methodPayment: [{ required: true, message: '支付方式必选！' }],
      },
    }
  },
  computed: {
    endTime() {
      if (Number(this.form.tenancyTerm) && this.form.startTime) {
        // "2021-03-30 00:00:00" => ['2021', '03', '30 00:00:00']
        const aaa = this.form.startTime.split('-')
        aaa[1] = Number(aaa[1]) + Number(this.form.tenancyTerm)
        aaa[0] = Number(aaa[0]) + Math.floor(aaa[1] / 12)
        aaa[1] = aaa[1] % 12
        aaa[1] = aaa[1] >= 10 ? aaa[1] : `0${aaa[1]}`
        return aaa.join('-')
      }
    },
    // 表单数据。调用接口实际传输的数据。
    formData() {
      const formData = {
        storeId: this.form.storeId,
        storeName: this.form.storeName,
        startTime: this.form.startTime,
        tenancyTerm: this.form.tenancyTerm,
        depositPayType: this.form.depositPayType,
        methodPayment: this.form.methodPayment,
      }
      if (this.id) {
        formData.orderNo = this.id
      }
      if (this.form.startTime) {
        formData.endTime = utils.parseTime(this.endTime)
      }
      if (this.chexing) {
        formData.longPlanId = this.chexing.longPlanId
        formData.deposit = this.chexing.deposit
        formData.rent = this.chexing.monthlyRent
        formData.amount =
          Math.floor(
            Number(this.chexing.monthlyRent) * Number(this.form.tenancyTerm)
          ) || ''
      }
      if (this.kehu) {
        formData.memberNo = this.kehu.memberNo
      }
      return formData
    },
    // 显示车辆信息表单
    showcheliangform() {
      // return true
      // 未选择门店
      if (!this.formData.storeId || !this.form.tenancyTerm) {
        return false
      }
      return true
    },
    // 显示客户信息表单
    showkehuform() {
      // 未显示车辆表单
      if (!this.showcheliangform) {
        return false
      }
      return true
    },
    // 显示其他信息表单
    showqitaform() {
      // 未显示客户表单
      if (!this.showkehuform) {
        return false
      }
      return true
    },
  },
  created() {
    if (this.id) {
      this.getData()
    }
  },
  methods: {
    /*
        |--------------------------------------------------------------------------
        | 初始化编辑订单数据
        |--------------------------------------------------------------------------
        */
    getData() {
      this.loading = true
      api.detail(this.id).then((response) => {
        this.form.storeId = response.data.orderInfo.takeStoreId // 取还车门店id
        this.form.storeName = response.data.orderInfo.takeStoreName // 取还扯门店名称
        this.form.startTime = response.data.orderInfo.rentalStartTime // 租赁开始时间
        this.form.tenancyTerm = response.data.orderInfo.tenancyTerm // 租期（月）
        this.form.depositPayType = Number(
          response.data.orderInfo.depositPayType
        ) // 押金支付类型（1.线上 2.线下 ）
        this.form.methodPayment = Number(response.data.orderInfo.methodPayment) // 支付方式  1.月付 2.一次性
        this.form.longPlanId = response.data.orderInfo.longPlanId
        this.form.memberNo = response.data.customerInfo.memberNo
        this.chexing = response.data.carInfo // 车辆信息
        this.paymentSupport =
          response?.data?.orderInfo?.paymentSupport
            ?.split(',')
            ?.map((val) => Number(val)) || []
        this.chexing.longPlanId = response.data.orderInfo.longPlanId // 长租方案id
        this.chexing.modelInfo = response.data.orderInfo.modelName // 车型信息
        this.chexing.deposit = response.data.orderInfo.deposit // 押金金额
        this.chexing.monthlyRent = response.data.orderInfo.rent // 月租金
        this.kehu = response.data.customerInfo // 客户信息
        this.loading = false
      })
    },

    /*
        |--------------------------------------------------------------------------
        | 时间禁用处理
        |--------------------------------------------------------------------------
        */
    disabledDate(date) {
      return (
        new Date().getTime() >= new Date(date).getTime() + 24 * 60 * 60 * 1000
      )
    },

    /*
        |--------------------------------------------------------------------------
        | 选择门店
        |--------------------------------------------------------------------------
        */
    submitmendian(data) {
      this.showmendian = false
      this.form.storeId = data.storeId
      this.form.storeName = data.storeName
      this.clearChexin()
    },

    /*
        |--------------------------------------------------------------------------
        | 车型部分
        |--------------------------------------------------------------------------
        */
    clearChexin() {
      this.chexing = {}
    },
    submitchenxing(data) {
      this.showchexing = false
      this.chexing = data
      console.log(data)
      this.form.longPlanId = data.longPlanId
      this.paymentSupport =
        data?.paymentSupport?.split(',')?.map((val) => Number(val)) || []
      console.log(this.paymentSupport)
      this.form.methodPayment = Number(this.paymentSupport[0])
    },

    /*
        |--------------------------------------------------------------------------
        | 客户部分
        |--------------------------------------------------------------------------
        */
    submitkehu(data) {
      this.showkehu = false
      this.kehu = data
      this.form.memberNo = data.memberNo
    },
    clickshowchexing(){
      api.classificationMoldelList({storeId:this.form.storeId,pageNum:1}).then((res) => {
        if(res.rows.length==0){
          this.$message.error('未查询到启用中的车型方案')
          return;
        }
        this.showchexing=true
      })
    },
    /*
        |--------------------------------------------------------------------------
        | 提交数据
        |--------------------------------------------------------------------------
        */
    emitData() {
      return new Promise((resolve) => {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            resolve(this.formData)
          }
        })
      })
    },
  },
}
</script>
